package me.zhengjie.timing.plc;

import lombok.RequiredArgsConstructor;
import me.zhengjie.WcsReport.WcsReportService;
import me.zhengjie.agvSend.AgvSendService;
import me.zhengjie.pojo.dto.*;
import me.zhengjie.pojo.entity.*;
import me.zhengjie.pojo.vo.TestVo;
import me.zhengjie.sqlservice.*;
import me.zhengjie.tcp.ChainLineTCP;
import me.zhengjie.utility.IdWorker;
import me.zhengjie.utility.liftState.PriorityEnum;
import me.zhengjie.utility.state.MaterialStatus;
import me.zhengjie.utility.state.TaskStatus;
import me.zhengjie.utility.state.TaskType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class ChainLineTaskTiming {
    private static final Logger chainLine = LoggerFactory.getLogger("chainLine");

    private final WcsChainLineConfigService wcsChainLineConfigService;

    private final ChainLineTCP chainLineTCP;

    private final IdWorker idWorker;

    private final WcsInboundMissionService wcsInboundMissionService;

    private final AgvSendService agvSendService;

    private final WcsReportService wcsReportService;

    private final IwsStoreOutsideService iwsSOutsideService;

    private final WcsInboundAbnormalMissionService wcsInboundAbnormalMissionService;

    private final NestingMiddleTableService nestingMiddleTableService;

    private final WcsLineEdgeWarehouseService wcsLineEdgeWarehouseService;

    private final WcsLineBodyAbnormalService wcsLineBodyAbnormalService;

    private final WcsAgvReleaseGoodsService wcsAgvReleaseGoodsService;

    //定时查询链条线
//    @Scheduled(fixedDelay = 1000)
    @Transactional
    public void chainLineTaskTiming() {
        //查询第一个位置的读码器是否有料
        List<WcsChainLineConfig> wcsChainLineConfigList = wcsChainLineConfigService.selectAll();
        for (WcsChainLineConfig wcsChainLineConfig : wcsChainLineConfigList) {
            Integer unitId = wcsChainLineConfig.getUnitId();
            Integer oneAddress = wcsChainLineConfig.getOneAddress();
            Integer oneReturnResult = wcsChainLineConfig.getOneReturnResult();
            Integer threeReturnResult = wcsChainLineConfig.getThreeReturnResult();
            Integer oneReturn = wcsChainLineConfig.getOneWritePlc();
            Integer twoReturn = wcsChainLineConfig.getTwoWritePlc();
//            Integer threesReturn = wcsChainLineConfig.getThreesReturn();
            Integer i = chainLineTCP.readHoldingRegisters(oneAddress, unitId);
            chainLine.info("第一段PLC读取是否有货返回值：{},地址位：{},设备id：{}", i,oneAddress,unitId);
            if (MaterialStatus.MATERIAL_STATUS_YES.getStatus().equals(i)) {
                if (oneReturn == 0){
                    Integer oneCodeInformation = wcsChainLineConfig.getOneCodeInformation();
                    //当前链条线上有料，查询中间表是否有嵌套，无嵌套返回NG
                    String s = chainLineTCP.readHoldingRegistersString(oneCodeInformation, unitId);
                    chainLine.info("读取到第一段地址位容器码：{}",s);
                    if (s != null) {
                        //1.发送wms查看栈板是否已入库
                        InboundIsCodeExistDto inboundIsCodeExist = new InboundIsCodeExistDto();
                        inboundIsCodeExist.setContainerCode(s);
                        inboundIsCodeExist.setNest(false);
                        boolean b = wcsReportService.inboundIsCodeExist(inboundIsCodeExist);
                        if (b) {
                            chainLineTCP.writeWithRetry(oneReturnResult, MaterialStatus.RETURN_ONE_RESULT_MATERIAL_EXIST.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                        }else {
                            //2.查询嵌套信息是否嵌套
//                        ReturnVo returnVo = wcsReportService.middleNestingData(s);
                            List<NestingMiddleTable> nestingMiddleTables = nestingMiddleTableService.selectContainerCode(s);
                            if (nestingMiddleTables.isEmpty()){
                                chainLineTCP.writeWithRetry(oneReturnResult, MaterialStatus.RETURN_ONE_RESULT_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                boolean b1 = wcsChainLineConfigService.updateOneReturnResultReturn(oneAddress,1);
                            }else {
                                //TODO是否为原物料Q，是需要检查一下是否有质检
                                //3.查询物料是否是原物料Q
                                long rawMaterialsQ = nestingMiddleTables.stream().filter(f -> f.getMaterialCategory().equals(TaskType.MATERIAL_Q.getMessage())).count();
                                if (rawMaterialsQ !=0){
                                    //判断是否自检
                                    long rawMaterialsQQualified = nestingMiddleTables.stream().filter(f -> f.getMaterialCategory().equals(TaskType.MATERIAL_Q.getMessage()) && f.getSelfCheckStatus().equals("合格")).count();
                                    if (rawMaterialsQ == rawMaterialsQQualified){
                                        //4.对比MES信息和WMS库存信息是否一致
                                        TestVo testVo = wcsReportService.wmsInventoryInformation(s);
                                        if (testVo.getCode() !=200){
                                            chainLineTCP.writeWithRetry(oneReturnResult, MaterialStatus.RETURN_ONE_RESULT_WMS_INVENTORY_INFORMATION_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                            boolean b1 = wcsChainLineConfigService.updateOneReturnResultReturn(oneAddress,1);
                                        }else {
                                            //对比库存信息 对比物料条码和数量
//                                        ArrayList<MiddleTable> mesMiddleTableList = (ArrayList<MiddleTable>) returnVo.getData();
                                            List<MaterialDao> materialDaoList = testVo.getData();
                                            HashSet<InventoryContrast> mesInventorySet = new HashSet<>();
                                            HashSet<InventoryContrast> wmsInventorySet = new HashSet<>();
                                            for (MaterialDao datum : materialDaoList) {
                                                InventoryContrast wmsInventory = new InventoryContrast();
                                                BeanUtils.copyProperties(datum,wmsInventory);
                                                wmsInventorySet.add(wmsInventory);
                                            }
                                            for (NestingMiddleTable middleTable : nestingMiddleTables) {
                                                InventoryContrast wmsInventory = new InventoryContrast();
                                                BeanUtils.copyProperties(middleTable,wmsInventory);
                                                mesInventorySet.add(wmsInventory);
                                            }

                                            if (!mesInventorySet.equals(wmsInventorySet)){
                                                //WMS和WES库存信息不一致
                                                chainLineTCP.writeWithRetry(oneReturnResult, MaterialStatus.RETURN_ONE_RESULT_MES_AND_WMS_INVENTORY_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                                boolean b1 = wcsChainLineConfigService.updateOneReturnResultReturn(oneAddress,1);
                                            }else {
                                                //库存一至
                                                chainLineTCP.writeWithRetry(oneReturnResult, MaterialStatus.RETURN_ONE_RESULT_YES.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                                boolean b1 = wcsChainLineConfigService.updateOneReturnResultReturn(oneAddress,1);
                                            }
                                        }
                                    }else {
                                        //自检不通过
                                        chainLineTCP.writeWithRetry(oneReturnResult, MaterialStatus.RETURN_ONE_RESULT_QUALITY_TESTING_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                    }   boolean b1 = wcsChainLineConfigService.updateOneReturnResultReturn(oneAddress,1);
                                }else {
                                    //4.对比MES信息和WMS库存信息是否一致
                                    TestVo testVo = wcsReportService.wmsInventoryInformation(s);
                                    if (testVo.getCode() !=200){
                                        chainLineTCP.writeWithRetry(oneReturnResult, MaterialStatus.RETURN_ONE_RESULT_WMS_INVENTORY_INFORMATION_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                        boolean b1 = wcsChainLineConfigService.updateOneReturnResultReturn(oneAddress,1);
                                    }else {
                                        //对比库存信息 对比物料条码和数量
//                                    ArrayList<MiddleTable> mesMiddleTableList = (ArrayList<MiddleTable>) returnVo.getData();
                                        List<MaterialDao> materialDaoList = testVo.getData();
                                        HashSet<InventoryContrast> mesInventorySet = new HashSet<>();
                                        HashSet<InventoryContrast> wmsInventorySet = new HashSet<>();
//                                    BeanUtils.copyProperties(nestingMiddleTables,mesInventorySet);
//                                    BeanUtils.copyProperties(wmsInventoryList,wmsInventorySet);
                                        for (MaterialDao datum : materialDaoList) {
                                            InventoryContrast wmsInventory = new InventoryContrast();
                                            BeanUtils.copyProperties(datum,wmsInventory);
                                            wmsInventorySet.add(wmsInventory);
                                        }
                                        for (NestingMiddleTable middleTable : nestingMiddleTables) {
                                            InventoryContrast wmsInventory = new InventoryContrast();
                                            BeanUtils.copyProperties(middleTable,wmsInventory);
                                            mesInventorySet.add(wmsInventory);
                                        }
                                        if (!mesInventorySet.equals(wmsInventorySet)){
                                            //WMS和WES库存信息不一致
                                            chainLineTCP.writeWithRetry(oneReturnResult, MaterialStatus.RETURN_ONE_RESULT_MES_AND_WMS_INVENTORY_NO.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                            boolean b1 = wcsChainLineConfigService.updateOneReturnResultReturn(oneAddress,1);
                                        }else {
                                            //库存一至
                                            chainLineTCP.writeWithRetry(oneReturnResult, MaterialStatus.RETURN_ONE_RESULT_YES.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                                            boolean b1 = wcsChainLineConfigService.updateOneReturnResultReturn(oneAddress,1);
                                        }
                                    }
                                }
                            }
                        }

                    }
                }
            }else if (MaterialStatus.MATERIAL_STATUS_NO.getStatus().equals(i)){
                //第一段无料，设置为0
                boolean b = wcsChainLineConfigService.updateOneReturnResultReturn(oneAddress,0);
            }

            //第二段地址位读到ok判断长宽高是否可入
            Integer twoAddress = wcsChainLineConfig.getTwoAddress();
            Integer twoInt = chainLineTCP.readHoldingRegisters(twoAddress, unitId);
            chainLine.info("第二段PLC限长宽高是否有货返回值：{}", twoInt);
            if (MaterialStatus.MATERIAL_STATUS_YES.getStatus().equals(twoInt)) {
                if (twoReturn == 0){
                    //长宽高检测是否合格
                    Integer length = wcsChainLineConfig.getLength();
                    Integer wide = wcsChainLineConfig.getWide();
                    Integer tall = wcsChainLineConfig.getTall();
                    //第三段储位号
                    String transportStorage = wcsChainLineConfig.getTransportStorage();
                    Integer lengthResult = chainLineTCP.readHoldingRegisters(length, unitId);
                    Integer wideResult = chainLineTCP.readHoldingRegisters(wide, unitId);
                    Integer tallResult = chainLineTCP.readHoldingRegisters(tall, unitId);
                    Integer twoCodeInformation = wcsChainLineConfig.getTwoCodeInformation();
                    String twoCode = chainLineTCP.readHoldingRegistersString(twoCodeInformation, unitId);
                    chainLine.info("第二段PLC限长宽高检测结果长：{},宽：{},高：{}", lengthResult, wideResult, tallResult);
                    if (Objects.equals(lengthResult, MaterialStatus.NOT_EXCEEDING.getStatus())
                            && Objects.equals(wideResult, MaterialStatus.NOT_EXCEEDING.getStatus())
                            && Objects.equals(tallResult, MaterialStatus.NOT_EXCEEDING.getStatus())) {
                        InboundStorageApplyDto1 inboundStorageApplyDto = new InboundStorageApplyDto1();
                        inboundStorageApplyDto.setContainerCode(twoCode);
                        inboundStorageApplyDto.setNest(false);
                        inboundStorageApplyDto.setFloor(TaskType.ONE_FLOOR.getMessage());
                        List<NestingMiddleTable> nestingMiddleTables = nestingMiddleTableService.selectContainerCode(twoCode);
                        ArrayList<NestingMiddleTable> materialDaos = new ArrayList<>();
                        for (NestingMiddleTable nestingMiddleTable : nestingMiddleTables) {
                            NestingMiddleTable nestingMiddleTable1 = new NestingMiddleTable();
                            BeanUtils.copyProperties(nestingMiddleTable,nestingMiddleTable1);
                            materialDaos.add(nestingMiddleTable1);
                        }
                        inboundStorageApplyDto.setData(materialDaos);
//                        if (!nestingMiddleTables.isEmpty()){
//                            NestingMiddleTable nestingMiddleTable = nestingMiddleTables.get(0);
//                            inboundStorageApplyDto.setWarehouse(nestingMiddleTable.getWarehouse());
//                            inboundStorageApplyDto.setIssuePosition(nestingMiddleTable.getIssuePosition());
//                        }
                        String storageCode = wcsReportService.inboundStorageApply(inboundStorageApplyDto);
                        // 向wms发送请求入库接口，拿到终点储位，异常储位点由WCS管控，未锁住终点储位
                        if (storageCode != null) {
                            NestingMiddleTable nestingMiddleTable = nestingMiddleTables.get(0);
                            WcsInboundMission wcsInboundMission = new WcsInboundMission();
                            String inboundCode = String.valueOf(idWorker.nextId());
                            wcsInboundMission.setInboundCode(inboundCode);
                            wcsInboundMission.setMissionStatus(TaskStatus.Task_create.getStatus());
                            wcsInboundMission.setContainerCode(twoCode);
                            wcsInboundMission.setSource(transportStorage);
                            wcsInboundMission.setDestination(storageCode);
                            wcsInboundMission.setContainerType(TaskType.PALLET.getStatus());
                            wcsInboundMission.setCreateTime(LocalDateTime.now());
                            wcsInboundMission.setUpdateTime(LocalDateTime.now());
                            wcsInboundMission.setInboundType(TaskType.inbound_ordinary.getStatus());
                            wcsInboundMission.setIsNest(0);
                            wcsInboundMission.setIsPlc(1);
                            StringBuilder sb = new StringBuilder();
                            List<String> materialCodeList = nestingMiddleTables.stream().map(NestingMiddleTable::getMaterialCode).distinct().collect(Collectors.toList());
                            for (String materialCode : materialCodeList) {
                                if (sb.length() >0){
                                    sb.append(",");
                                }
                                sb.append(materialCode);
                            }
                            String materIalCode = sb.toString();
                            wcsInboundMission.setMaterialCode(materIalCode);
                            wcsInboundMission.setIsWms(1);
                            boolean b = wcsInboundMissionService.insertInbound(wcsInboundMission);
                            if (!b) {
                                chainLine.info("创建入库任务失败");
                                throw new RuntimeException("创建入库任务失败");
                            }
                        } else {
                            //查询1楼异常区空闲储位
//                            List<IwsSOutside> iwsSLocals = iwsSOutsideService.selectStoreTypeStatus(TaskType.STORAGE_TYPE_ONE_FLOOR_NEW_ABNORMAL.getMessage(), 0);
                            List<WcsLineEdgeWarehouse> wcsLineEdgeWarehouses = wcsLineEdgeWarehouseService.selectRegionAndStatus(TaskType.STORAGE_TYPE_ONE_FLOOR_NEW_ABNORMAL.getMessage(), TaskStatus.LINE_EDGE_WAREHOUSE_IDLE.getStatus());
                            if (!wcsLineEdgeWarehouses.isEmpty()) {
                                WcsLineEdgeWarehouse wcsLineEdgeWarehouse = wcsLineEdgeWarehouses.get(0);
//                                String sId = iwsSLocal.getId();
                                String sId = wcsLineEdgeWarehouse.getStorageCode();
                                //终点储位为null，走异常流程
//                            WcsInboundMission wcsInboundMission = new WcsInboundMission();
                                WcsInboundAbnormalMission wcsInboundAbnormalMission = new WcsInboundAbnormalMission();
                                String inboundCode = String.valueOf(idWorker.nextId());
                                wcsInboundAbnormalMission.setAbnormalCode(inboundCode);
                                wcsInboundAbnormalMission.setMissionStatus(TaskStatus.Task_create.getStatus());
                                wcsInboundAbnormalMission.setContainerCode(twoCode);
                                wcsInboundAbnormalMission.setSource(transportStorage);
                                wcsInboundAbnormalMission.setDestination(sId);
                                wcsInboundAbnormalMission.setContainerType(TaskType.PALLET.getStatus());
                                wcsInboundAbnormalMission.setCreateTime(LocalDateTime.now());
                                wcsInboundAbnormalMission.setUpdateTime(LocalDateTime.now());
                                wcsInboundAbnormalMission.setAbnormal("库内无储位");
                                boolean b = wcsInboundAbnormalMissionService.insertAbnormal(wcsInboundAbnormalMission);
                                if (!b) {
                                    chainLine.info("创建入库任务失败");
                                    throw new RuntimeException("创建入库任务失败");
                                }
                                //将终点储位锁住
                                boolean b1 = iwsSOutsideService.updateStatus(sId,null,1);
                                if (!b1){
                                    chainLine.info("异常流程,锁终点储位失败");
                                    throw new RuntimeException("异常流程,锁终点储位失败");
                                }
                                WcsLineBodyAbnormal wcsLineBodyAbnormal = new WcsLineBodyAbnormal();
                                wcsLineBodyAbnormal.setContainerCode(twoCode);
                                wcsLineBodyAbnormal.setAbnormalInformation("库内无储位");
                                wcsLineBodyAbnormal.setCreateTime(LocalDateTime.now());
                                boolean b2 = wcsLineBodyAbnormalService.inertAbnormal(wcsLineBodyAbnormal);
                                if (!b2) {
                                    chainLine.error("创建线条异常数据失败");
                                    throw new RuntimeException("创建线条异常数据失败");
                                }
                            }
                        }
                        //向TCP返回长宽高通过
                        Integer twoReturnResult = wcsChainLineConfig.getTwoReturnResult();
                        chainLineTCP.writeWithRetry(twoReturnResult, MaterialStatus.OK.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                        boolean b2 = wcsChainLineConfigService.updateTwoReturnResultReturn(twoAddress,1);
                    } else  if (Objects.equals(lengthResult, MaterialStatus.EXCEEDING.getStatus())
                            || Objects.equals(wideResult, MaterialStatus.EXCEEDING.getStatus())
                            || Objects.equals(tallResult, MaterialStatus.EXCEEDING.getStatus())) {
                        //查询1楼异常区空闲储位
//                        List<IwsSOutside> iwsSLocals = iwsSOutsideService.selectStoreTypeStatus(TaskType.STORAGE_TYPE_ONE_FLOOR_NEW_ABNORMAL.getMessage(), 0);
                        List<WcsLineEdgeWarehouse> wcsLineEdgeWarehouses = wcsLineEdgeWarehouseService.selectRegionAndStatus(TaskType.STORAGE_TYPE_ONE_FLOOR_NEW_ABNORMAL.getMessage(), TaskStatus.LINE_EDGE_WAREHOUSE_IDLE.getStatus());
                        if (!wcsLineEdgeWarehouses.isEmpty()) {
                            WcsLineEdgeWarehouse wcsLineEdgeWarehouse = wcsLineEdgeWarehouses.get(0);
//                            String sId = iwsSLocal.getId();
                            String sId = wcsLineEdgeWarehouse.getStorageCode();
                            //终点储位为null，走异常流程
//                        WcsInboundMission wcsInboundMission = new WcsInboundMission();
                            WcsInboundAbnormalMission wcsInboundAbnormalMission = new WcsInboundAbnormalMission();
                            String inboundCode = String.valueOf(idWorker.nextId());
                            wcsInboundAbnormalMission.setAbnormalCode(inboundCode);
                            wcsInboundAbnormalMission.setMissionStatus(TaskStatus.Task_create.getStatus());
                            wcsInboundAbnormalMission.setContainerCode(twoCode);
                            wcsInboundAbnormalMission.setSource(transportStorage);
                            wcsInboundAbnormalMission.setDestination(sId);
                            wcsInboundAbnormalMission.setContainerType(TaskType.PALLET.getStatus());
                            wcsInboundAbnormalMission.setCreateTime(LocalDateTime.now());
                            wcsInboundAbnormalMission.setUpdateTime(LocalDateTime.now());
                            String abnormal = "";
                            if (!Objects.equals(lengthResult, MaterialStatus.NOT_EXCEEDING.getStatus())) {
                                abnormal += "过高";
                            } else if (!Objects.equals(wideResult, MaterialStatus.NOT_EXCEEDING.getStatus())) {
                                abnormal += "过宽";
                            } else if (Objects.equals(tallResult, MaterialStatus.NOT_EXCEEDING.getStatus())) {
                                abnormal += "过高";
                            }

                            wcsInboundAbnormalMission.setAbnormal(abnormal);
                            boolean b = wcsInboundAbnormalMissionService.insertAbnormal(wcsInboundAbnormalMission);
                            if (!b) {
                                chainLine.error("创建入库任务失败");
                                throw new RuntimeException("创建入库任务失败");
                            }
                            //将终点储位锁住
                            boolean b1 = iwsSOutsideService.updateStatus(sId,null,1);
                            if (!b1){
                                chainLine.error("异常流程,锁终点储位失败");
                                throw new RuntimeException("异常流程,锁终点储位失败");
                            }
                            WcsLineBodyAbnormal wcsLineBodyAbnormal = new WcsLineBodyAbnormal();
                            wcsLineBodyAbnormal.setContainerCode(twoCode);
                            wcsLineBodyAbnormal.setAbnormalInformation(abnormal);
                            wcsLineBodyAbnormal.setCreateTime(LocalDateTime.now());
                            boolean b3 = wcsLineBodyAbnormalService.inertAbnormal(wcsLineBodyAbnormal);
                            if (!b3) {
                                chainLine.error("创建线条异常数据失败");
                                throw new RuntimeException("创建线条异常数据失败");
                            }
                            //向TCP返回长宽高通过
                            Integer twoReturnResult = wcsChainLineConfig.getTwoReturnResult();
                            chainLineTCP.writeWithRetry(twoReturnResult, MaterialStatus.OK.getStatus(), unitId, MaterialStatus.RETRY_COUNT.getStatus());
                            boolean b2 = wcsChainLineConfigService.updateTwoReturnResultReturn(twoAddress,1);
                        }
                    }
                }
            }else if (MaterialStatus.MATERIAL_STATUS_NO.getStatus().equals(twoInt)){
                boolean b = wcsChainLineConfigService.updateTwoReturnResultReturn(twoAddress,0);
            }

            //第三段任务
            Integer threeAddress = wcsChainLineConfig.getThreeAddress();
            Integer threeInt = chainLineTCP.readHoldingRegisters(threeAddress, unitId);
            chainLine.info("第三段PLC读取是否有货返回值：{}", threeInt);
            if (MaterialStatus.MATERIAL_STATUS_YES.getStatus().equals(threeInt)) {
                //判断agv是否运行搬运
                Integer tcpTransport = wcsChainLineConfig.getTcpTransport();
                Integer tcpTransportResult = chainLineTCP.readHoldingRegisters(tcpTransport, unitId);
                if (MaterialStatus.TCP_CARRY_YES.getStatus().equals(tcpTransportResult)) {
                    //tcp允许搬运读取容器编码
                    Integer threeCodeInformation = wcsChainLineConfig.getThreeCodeInformation();
                    String threeCode = chainLineTCP.readHoldingRegistersString(threeCodeInformation, unitId);
                    //根据容器编码查询任务
                    List<WcsInboundMission> wcsInboundMissionList = wcsInboundMissionService.selectContainerCode(threeCode);
                    List<WcsInboundAbnormalMission> wcsInboundAbnormalMissionList = wcsInboundAbnormalMissionService.selectContainerCode(threeCode);
                    if (!wcsInboundMissionList.isEmpty()) {
                        WcsInboundMission wcsInboundMission = wcsInboundMissionList.get(0);

                        AgvTaskSubmitDto agvTaskSubmitDto = new AgvTaskSubmitDto();
                        //todo 任务类型，根据现场情况来定
                        agvTaskSubmitDto.setTaskType(TaskType.PF_FMR_COMMON.getMessage());
                        ArrayList<TargetRoute> targetRouteList = new ArrayList<>();
                        TargetRoute targetRoute = new TargetRoute();
                        TargetRoute targetRoutes = new TargetRoute();
                        //添加起点
                        targetRoute.setSeq(0);
                        targetRoute.setType(TaskType.SITE.getMessage());
                        targetRoute.setCode(wcsInboundMission.getSource());
                        //添加终点
                        targetRoutes.setSeq(1);
                        targetRoutes.setType(TaskType.STORAGE.getMessage());
                        targetRoutes.setCode(wcsInboundMission.getDestination());
                        targetRouteList.add(targetRoute);
                        targetRouteList.add(targetRoutes);
                        agvTaskSubmitDto.setTargetRoute(targetRouteList);
                        agvTaskSubmitDto.setRobotTaskCode(wcsInboundMission.getInboundCode());
                        agvTaskSubmitDto.setInitPriority(PriorityEnum.FOUR.getWeight());

                        CarrierInfoDto carrierInfoDto = new CarrierInfoDto();
                        carrierInfoDto.setCarrierCode(wcsInboundMission.getContainerCode());
                        carrierInfoDto.setCarrierType(TaskType.ONE_assignment_Container_binding.getMessage());
                        ArrayList<CarrierInfoDto> carrierInfoDtos = new ArrayList<>();
                        carrierInfoDtos.add(carrierInfoDto);
                        ExtraDto extraDto = new ExtraDto();
                        extraDto.setCarrierInfo(carrierInfoDtos);
                        agvTaskSubmitDto.setExtra(extraDto);
                        String taskCode = agvSendService.agvTaskSubmit(agvTaskSubmitDto);
                        if (taskCode != null) {
                            WcsAgvReleaseGoods wcsAgvReleaseGoods = new WcsAgvReleaseGoods();
                            wcsAgvReleaseGoods.setTaskCode(wcsInboundMission.getInboundCode());
                            wcsAgvReleaseGoods.setCreateTime(LocalDateTime.now());
                            wcsAgvReleaseGoods.setApplyReleaseGoodsStatus(TaskStatus.APPLY_RELEASE_GOODS_DEFAULT.getStatus());
                            wcsAgvReleaseGoods.setPattern(TaskStatus.PATTERN_PICK_UP.getStatus());
                            wcsAgvReleaseGoods.setFloor(TaskType.ONE_FLOOR.getStatus());
                            boolean b3 = wcsAgvReleaseGoodsService.insert(wcsAgvReleaseGoods);
                            //向plc写入AGV执行中
//                            chainLineTCP.writeWithRetry(threeReturnResult,MaterialStatus.AGV_TRANSPORT_IN_THE_TASK.getStatus(),unitId,MaterialStatus.RETRY_COUNT.getStatus());
                            //通知AGV成功，修改任务状态
                            boolean b = wcsInboundMissionService.updateMissionStatus(taskCode, TaskStatus.task_send.getStatus());
                            if (!b) {
                                chainLine.error("数据库异常,修改数据库失败");
                                throw new RuntimeException("数据库异常,修改数据库失败");
                            }
                        }

                    }else if (!wcsInboundAbnormalMissionList.isEmpty()){
                        WcsInboundAbnormalMission wcsInboundAbnormalMission = wcsInboundAbnormalMissionList.get(0);
                        AgvTaskSubmitDto agvTaskSubmitDto = new AgvTaskSubmitDto();
                        //todo 任务类型，根据现场情况来定
                        agvTaskSubmitDto.setTaskType(TaskType.PF_FMR_COMMON.getMessage());
                        ArrayList<TargetRoute> targetRouteList = new ArrayList<>();
                        TargetRoute targetRoute = new TargetRoute();
                        TargetRoute targetRoutes = new TargetRoute();
                        //添加起点
                        targetRoute.setSeq(0);
                        targetRoute.setType(TaskType.SITE.getMessage());
                        targetRoute.setCode(wcsInboundAbnormalMission.getSource());
                        //添加终点
                        targetRoutes.setSeq(1);
                        targetRoutes.setType(TaskType.SITE.getMessage());
                        targetRoutes.setCode(wcsInboundAbnormalMission.getDestination());
                        targetRouteList.add(targetRoute);
                        targetRouteList.add(targetRoutes);
                        agvTaskSubmitDto.setTargetRoute(targetRouteList);
                        agvTaskSubmitDto.setRobotTaskCode(wcsInboundAbnormalMission.getAbnormalCode());
                        agvTaskSubmitDto.setInitPriority(PriorityEnum.FOUR.getWeight());

                        CarrierInfoDto carrierInfoDto = new CarrierInfoDto();
                        carrierInfoDto.setCarrierCode(wcsInboundAbnormalMission.getContainerCode());
                        carrierInfoDto.setCarrierType(TaskType.ONE_assignment_Container_binding.getMessage());
                        ArrayList<CarrierInfoDto> carrierInfoDtos = new ArrayList<>();
                        carrierInfoDtos.add(carrierInfoDto);
                        ExtraDto extraDto = new ExtraDto();
                        extraDto.setCarrierInfo(carrierInfoDtos);
                        agvTaskSubmitDto.setExtra(extraDto);
                        String taskCode = agvSendService.agvTaskSubmit(agvTaskSubmitDto);
                        if (taskCode != null) {
                            WcsAgvReleaseGoods wcsAgvReleaseGoods = new WcsAgvReleaseGoods();
                            wcsAgvReleaseGoods.setTaskCode(wcsInboundAbnormalMission.getAbnormalCode());
                            wcsAgvReleaseGoods.setCreateTime(LocalDateTime.now());
                            wcsAgvReleaseGoods.setApplyReleaseGoodsStatus(TaskStatus.APPLY_RELEASE_GOODS_DEFAULT.getStatus());
                            wcsAgvReleaseGoods.setPattern(TaskStatus.PATTERN_PICK_UP.getStatus());
                            wcsAgvReleaseGoods.setFloor(TaskType.ONE_FLOOR.getStatus());
                            boolean b3 = wcsAgvReleaseGoodsService.insert(wcsAgvReleaseGoods);
//                            chainLineTCP.writeWithRetry(threeReturnResult,MaterialStatus.AGV_TRANSPORT_IN_THE_TASK.getStatus(),unitId,MaterialStatus.RETRY_COUNT.getStatus());
                            //通知AGV成功，修改任务状态
                            boolean b = wcsInboundAbnormalMissionService.updateMissionStatus(taskCode, TaskStatus.task_send.getStatus());
                            if (!b) {
                                chainLine.error("数据库异常,修改数据库失败");
                                throw new RuntimeException("数据库异常,修改数据库失败");
                            }
                        }
                    }
                }
            }

        }
    }
}
